from flask import jsonify, request
from app.auth.auths import Auth
from app.qiniu.token import upload, get_token, delete_qiniu
from .. import common
import json

# access_key = 'Tg9vbJMCK7eQ0eye7vEHcDG49bveyvWejJKoMVAq'
# secret_key = '4SKloJujVhUlWXZpdzu56Dk3RuER6DiWf4T'


def init_api(app):
    @app.route('/filetoken', methods=['GET'])
    def token():
        result = Auth.identify(Auth, request)
        if result['status'] and result['data']:
            result = common.trueReturn(get_token(), '获取token成功')
        return jsonify(result)

    @app.route('/file/upload', methods=['POST'])
    def upload_file():
        #构建鉴权对象
        res = upload(request.files.get('file'))
        result = json.loads(res[1].text_body)
        # print(result)
        obj = {
            'url': 'http://pb88oxchv.bkt.clouddn.com/' + result['key']
        }
        if res[1].status_code == 200:
            return jsonify(common.trueReturn(obj, '文件上传成功'))
        else:
            return jsonify(common.falseReturn(result, '文件上传失败'))

    @app.route('/file/delete/<key>', methods=['delete'])
    def delete_file(key):
        res = delete_qiniu(key)
        if res.status_code == 200:
            return jsonify(common.trueReturn('', '文件删除成功'))
        else:
            return jsonify(common.falseReturn(json.loads(res.text_body), '文件删除失败'))
